package com.example.security.handle;

import com.alibaba.fastjson.JSONObject;
import com.example.security.component.JwtTokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/5/29 19:35
 * @version: 0.1
 * @Description :
 * @Modified By:
 */

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private JwtTokenManager jwtTokenManager;
    private RedisTemplate redisTemplate;
    public MyAuthenticationSuccessHandler(JwtTokenManager jwtTokenManager,RedisTemplate redisTemplate) {
        this.jwtTokenManager = jwtTokenManager;
        this.redisTemplate = redisTemplate;
    }

    private static final Logger log = LoggerFactory.getLogger(MyAuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest req,HttpServletResponse res,Authentication authentication) throws IOException, ServletException {

        ResponseMsg.response(res,map->{
            map.put("code",HttpStatus.OK.value());
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String jwtToken = jwtTokenManager.createToken(userDetails.getUsername());
            String userJson= JSONObject.toJSONString(userDetails);
            redisTemplate.opsForValue().set(jwtToken, userJson,1L,TimeUnit.HOURS );
            log.info("userDetails:{},jwtToken:{}",userDetails,jwtToken);
            map.put("token",jwtToken);
            map.put("msg","登录成功");
        });

    }


}
